from flask import Flask, request, redirect, url_for
from flask_admin import Admin, AdminIndexView, expose
import flask_login as login




class CustomIndexView(AdminIndexView):
    """ 自定义flask-admin首页-处理登录逻辑"""

    @expose('/')
    def index(self):
        return self.render('admin/custom_index.html')

    @expose('/login/', methods=('GET', 'POST'))
    def login_view(self):
        # handle user login
        from task_app.models import User
        login_name = request.form.get('login_name', '')
        login_pwd = request.form.get('login_pwd', '')
        if login.current_user.is_authenticated:
            return redirect(url_for('.index'))
        user = User.query.filter_by(username=login_name).first()
        if user is not None and user.verify_password(login_pwd):
            msg = 'Account is locked.'
            if login.login_user(user):
                msg = 'Login sucess.'
        else:
            msg = 'Invalid email or password.'
        self._template_args['msg'] = msg
        return self.render('admin/custom_index.html')

    @expose('/logout/')
    def logout_view(self):
        login.logout_user()
        return redirect(url_for('.index'))


admin = Admin(
    name='后台管理系统',
    index_view=CustomIndexView(name='欢迎页'),
    base_template='admin/custom/layout.html',
    template_mode='bootstrap3'
)


def init_admin(app: Flask):
    admin.init_app(app)
    from extensions import db
    # task_app admin_views
    from task_app.admin import JobPlanModelView,JobEvenModelView
    from task_app.models import JobPlan,JobEvent
    admin.add_view(JobPlanModelView(JobPlan, db.session, name='定时计划'))
    admin.add_view(JobEvenModelView(JobEvent, db.session, name='定时事件'))
    # xx_app admin_views
    # ...

